package tcm.com.gistone.controller;

import javafx.stage.StageStyle;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tcm.com.gistone.database.config.GetBySqlMapper;
import tcm.com.gistone.database.entity.*;
import tcm.com.gistone.database.mapper.*;
import tcm.com.gistone.util.*;

import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;


/**
 * @Author:renqiang
 * @Param:
 * @Description:文件上传下载
 * @Date:14:48 2017/8/12
 */
@RestController
@RequestMapping( "file" )
@Transactional
public class FileController {

    /**
     * 允许上传的扩展名
     */
    private final static org.slf4j.Logger logger = LoggerFactory.getLogger(ClientUtil.class);
    private static String[] extensionPermit = {"xls", "xlsx"};
    private static String[] extensionPermit1 = {"jpg", "png", "bmp"};
    private static String[] extensionPermit2 = {"zip"};
    private static String[] extensionPermit3 = {"xml"};
    @Autowired
    private BookinfoMapper bm;
    @Autowired
    private SpecialMapper sm;
    @Autowired
    private ThemeMapper tm;
    @Autowired
    private WordMapper wm;
    @Autowired
    private GetBySqlMapper gm;
    @Autowired
    private WarmKnowledgeMapper wkm;
    @Autowired
    private UrlUtil urlUtil;
    @Autowired
    private ConfigUtil configUtil;

    private ResourceLoader resourceLoader;

    public static String fileDir;

    public static String logDir;


    /*上级书籍文件*/
//    @CrossOrigin(origins = "*")
    @RequestMapping( value = "uploadBook", method = RequestMethod.POST )
    @Transactional( rollbackFor = Exception.class )
    public EdatResult uploadBook(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String zipPath = "";
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            long bookId = Long.parseLong(request.getParameter("bookId"));
            long specialId = Long.parseLong(request.getParameter("specialId"));
            Bookinfo bookinfo = bm.selectByPrimaryKey(bookId);
            Special special = sm.selectByPrimaryKey(specialId);
            String bookName = bookinfo.getBookName();
            if (null == bookinfo) {
                return EdatResult.build(1, "未录入书目");
            }
            logger.info("开始上传古籍" + bookName + "的相关文件");
            long t1 = System.currentTimeMillis();
            Map map = new HashMap();
            File saveDirectory = new File(fileDir);
            String dirName = "Files/Books/" + special.getSpecialName() + "/" + bookinfo.getBookName();
            String bookPath = fileDir + "/" + dirName;
            bookinfo.setDirUrl(dirName.replaceAll("\\\\", "/"));
            File bookDirectory = new File(bookPath);
            Collection<Part> parts = request.getParts();
            for (Part part : parts) {
                String fileType = part.getName();
                String fileName = part.getSubmittedFileName();
                if (fileName != null) {
                    InputStream is = part.getInputStream();
                    if (fileType.equals("file")) {/*正文文件*/
                        String fileExtension = FilenameUtils.getExtension(fileName);
                        if (!Arrays.asList(extensionPermit).contains(fileExtension)) {
                            return EdatResult.build(1, "正文文件格式错误");
                        }
                        File dir = new File(bookPath + "/section");
                        FileUtils.copyInputStreamToFile(is, new File(bookPath + "/section", fileName));
                        map.put("sectionPath", bookPath + "/section/" + fileName);
                        bookinfo.setSectionFile(fileName);
                    } else if (fileType.equals("file2")) {/*图片文件*/
                        String fileExtension = FilenameUtils.getExtension(fileName);
                        if (!Arrays.asList(extensionPermit2).contains(fileExtension)) {
                            return EdatResult.build(1, "正文图片文件格式错误");
                        }
                        File dir = new File(bookPath + "/images");
                        FileUtils.copyInputStreamToFile(is, new File(bookPath + "/images", fileName));
                        ZipUtil.unZipFiles(bookPath + "/images/" + fileName, bookPath + "/images/pics");
                        // Zipper.unzip(bookPath + "/images/" + fileName, bookPath + "/images/pics");
                        map.put("imagesPath", bookPath + "/images/pics");
                        bookinfo.setImagesFile(fileName);
                    } else if (fileType.equals("file3")) {/*图文映射文件*/
                        String fileExtension = FilenameUtils.getExtension(fileName);
                        bookinfo.setMappingFile(fileName);
                        if (!Arrays.asList(extensionPermit).contains(fileExtension)) {
                            return EdatResult.build(1, "图文映射文件格式错误");
                        }
                        File dir3 = new File(bookPath + "/mapping");
                        FileUtils.copyInputStreamToFile(is, new File(bookPath + "/mapping", fileName));
                        map.put("mappingPah", bookPath + "/mapping" + fileName);
                        bookinfo.setMappingFile(fileName);
                    } else if (fileType.equals("file4")) {/*知识提取文件*/
                        String fileExtension = FilenameUtils.getExtension(fileName);
                        if (!Arrays.asList(extensionPermit).contains(fileExtension)) {
                            return EdatResult.build(1, "知识提取文件格式错误");
                        }
                        File dir3 = new File(bookPath + "/knowledge");
                        FileUtils.copyInputStreamToFile(is, new File(bookPath + "/knowledge", fileName));
                        map.put("knowledgePath", bookPath + "/knowledge" + fileName);
                        bookinfo.setKnowledgeFile(fileName);
                    }
                }
            }
            bookinfo.setStatus(1);/*更改状态为已上传*/
            bm.updateByPrimaryKey(bookinfo);
            long t2 = System.currentTimeMillis();
            logger.info("古籍" + bookName + "的相关文件上传完成，耗时：" + (t2 - t1)/1000 + "s");
            return EdatResult.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            //   FileUtil.delete(zipPath);
        }
    }

    /*上传主题词文件*/
    @CrossOrigin( origins = "*" )
    @RequestMapping( value = "uploadWord", method = RequestMethod.POST )
    public EdatResult wordUpload(@RequestParam( "file" ) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            long specialId = Long.parseLong(request.getParameter("specialId"));
            Special special = sm.selectByPrimaryKey(specialId);
            String specialName = special.getSpecialName();
            logger.info("开始上传" + specialName + "专题文件");
            long t1 = System.currentTimeMillis();
            String dirName = "Files/Words/" + specialName;
            String dirPath = fileDir + dirName;
            File bookDirectory = new File(dirPath);
            File zipDir = new File(dirPath + "/zipFile");
            if (!file.isEmpty()) {
                String fileName1 = file.getOriginalFilename();
                String fileExtension = FilenameUtils.getExtension(fileName1);
                String fileName = specialName + "." + fileExtension;
                if (!Arrays.asList(extensionPermit2).contains(fileExtension)) {
                    return EdatResult.build(1, "文件格式错误");
                }
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File((dirPath + "/zipFile"), fileName));
                List<String> list1 = tm.selectNameBySpecial(specialId);/*主题词所有类型*/
                List<String> list2 = new ArrayList<>(list1);
                /*压缩文件内容校验*/
                InputStream in2 = file.getInputStream();
                byte[] b = new byte[3];
                in2.read(b);
                in2.close();
                ZipFile zip = null;
                if (b[0] == -17 && b[1] == -69 && b[2] == -65)
                    zip = new ZipFile(dirPath + "/zipFile/" + fileName, Charset.forName("UTF-8"));//解决中文文件夹乱码
                else zip = new ZipFile(dirPath + "/zipFile/" + fileName, Charset.forName("GBK"));//解决中文文件夹乱码
                for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
                    ZipEntry entry = (ZipEntry) entries.nextElement();
                    String zipEntryName = entry.getName();
                    if (entry.isDirectory()) {
                    } else {
                        if (list1.contains(getPrefix(zipEntryName))) {
                            list1.remove(getPrefix(zipEntryName));
                        }
                    }
                }
                if (list1.size() > 0) {
                    return EdatResult.build(1, "缺少文件:" + list1);

                }
                File dir = new File(dirPath + "/dataFiles");
                /*删除之前的文件*/
                for (File file1 : dir.listFiles()) {
                    FileUtil.delete(file1.getAbsolutePath());
                }
                ZipUtil.unZipFiles(dirPath + "/zipFile/" + fileName, dirPath + "/dataFiles");
                File[] files = dir.listFiles();
                for (int n = 0; n < files.length; n++) {
                    File ff = files[n];
                    if (ff.isFile()) {
                        String name = ff.getName();
                        String name1 = getPrefix(name);/*获取文件名称*/
                        if (list2.contains(name1)) {
                            list2.remove(name1);
                            ff.renameTo(new File(dirPath + "/dataFiles/" + name1 + ".xls"));
                        } else {
                        }
                    }
                }
                special.setUrl(dirName);
                sm.updateByPrimaryKey(special);
                long t2 = System.currentTimeMillis();
                logger.info(specialName + "专题文件上传完成,耗时：" + (t2 - t1)/1000 + "s");
                return EdatResult.ok();
            } else {
                logger.error(specialName + "专题文件上传失败");
                return EdatResult.build(1, "文件上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "文件上传失败");
        } finally {
        }
    }

    /*上传温病专家知识提取文件*/
    @CrossOrigin( origins = "*" )
    @RequestMapping( value = "uploadWarmKnowledge", method = RequestMethod.POST )
    public EdatResult uploadWarmKnowledge(@RequestParam( "file" ) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            logger.info("开始上传温病专家知识提取文件");
            long t1 = System.currentTimeMillis();
            File saveDirectory = new File(fileDir);
            String dirName = "Files/Knowledge/温病";
            String dirPath = fileDir + dirName;
            File bookDirectory = new File(dirPath);
            File zipDir = new File(dirPath + "/zipFile");
            List<String> types = new ArrayList<>();/*温病专家知识提取类型*/
            types.add("中药");
            types.add("证候");
            types.add("方剂");
            types.add("疾病");
            types.add("治法");
            if (!file.isEmpty()) {
                String fileName1 = file.getOriginalFilename();
                String fileExtension = FilenameUtils.getExtension(fileName1);
                String fileName = "温病." + fileExtension;
                if (!Arrays.asList(extensionPermit2).contains(fileExtension)) {
                    return EdatResult.build(1, "文件格式错误");
                }
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File((dirPath + "/zipFile"), fileName));
                ZipUtil.unZipFiles(dirPath + "/zipFile/" + fileName, dirPath + "/dataFiles");
                File dir = new File(dirPath + "/dataFiles");
                File[] files = dir.listFiles();
                for (int n = 0; n < files.length; n++) {
                    File ff = files[n];
                    if (ff.isFile()) {
                        String name = ff.getName();
                        String name1 = getPrefix(name);
                        if (types.contains(name1)) {
                            /*录入数据*/
                            recordWarnKonwledge(ff.getAbsolutePath(), name1);
                            types.remove(name1);
                        } else {
                            /*删除多余文件*/
                            FileUtil.delete(ff.getAbsolutePath());
                        }
                    }
                }
                long t2 = System.currentTimeMillis();
                logger.info("温病专题文件上传完成,耗时：" + (t2 - t1)/1000 + "s");
                return EdatResult.ok();
            } else {
                logger.error("温病专题文件上传失败");
                return EdatResult.build(1, "文件上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return EdatResult.build(1, "文件上传失败");
        } finally {
        }
    }

    /*录入温病专家知识*/
    private void recordWarnKonwledge(String url, String name) throws IOException {
        Workbook book = null;
        try {
            logger.info("开始录入温病专家知识");
            long t1 = System.currentTimeMillis();
            book = ExcelUtil.getExcelWorkbook(url);
            Sheet sheet = book.getSheetAt(0);
            if (sheet == null) {
                logger.error("数据错误");
                return;
            }
            int firstRowNum = sheet.getFirstRowNum();
            int lastRowNum = sheet.getLastRowNum();
            List<WarmKnowledge> list = new ArrayList<>();
            String fname = "";
            for (int i = firstRowNum + 1; i <= lastRowNum; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    WarmKnowledge knowledge = new WarmKnowledge();
                    if (!ExcelUtil.getCellValue(row.getCell(0)).equals("")) {
                        fname = ExcelUtil.getCellValue(row.getCell(0));
                    }
                    knowledge.setWord(fname);
                    knowledge.setType(name);
                    knowledge.setSecDisease(ExcelUtil.getCellValue(row.getCell(3)));
                    knowledge.setAlias(ExcelUtil.getCellValue(row.getCell(1)));
                    knowledge.setDisease(ExcelUtil.getCellValue(row.getCell(2)));
                    knowledge.setCausePathogenesis(ExcelUtil.getCellValue(row.getCell(4)));
                    knowledge.setSymptoms(ExcelUtil.getCellValue(row.getCell(5)));
                    knowledge.setSyndrome(ExcelUtil.getCellValue(row.getCell(6)));
                    knowledge.setCureMethod(ExcelUtil.getCellValue(row.getCell(7)));
                    knowledge.setPrescription(ExcelUtil.getCellValue(row.getCell(8)));
                    knowledge.setChineseMedicine(ExcelUtil.getCellValue(row.getCell(9)));
                    knowledge.setMedicalBook(ExcelUtil.getCellValue(row.getCell(10)));
                    knowledge.setMedicalPerson(ExcelUtil.getCellValue(row.getCell(11)));
                    list.add(knowledge);
                }
            }
            if (list.size() > 0) {
                wkm.insertBatch(list);
            }
            long t2 = System.currentTimeMillis();
            logger.info("结束录入温病专家知识，耗时：" + (t2 - t1)/1000 + "s");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            book.close();
        }
    }

    //获取文件名称
    public String getPrefix(String fileName) {
        int l = FilenameUtils.indexOfExtension(fileName);
        return fileName.substring(0, l);
    }

    /*从数据库导出主题词到excel*/
    public boolean exportWords(long specialId) throws IOException {
        Special special = sm.selectByPrimaryKey(specialId);
        String url = fileDir + "Files/Words/" + special.getSpecialName();
        String specialName = special.getSpecialName();
        logger.info("开始导出" + specialName + "专题词表");
        long t1 = System.currentTimeMillis();
        List<Theme> list = tm.selectThemeBySpecial(specialId);
        if (list.size() < 1) {
            logger.info("查不到专题下主题类型");
            return false;
        }
        int num = 0;//主题词总数
        File file3 = new File(url + "/dataFiles");
        if (!file3.exists()) {
            file3.mkdirs();
        }
        for (Theme theme : list) {
            String name = theme.getThemeName();
            List<Word> list1 = wm.selectByType(theme.getThemeId());/*获取所有该类型的主题词*/
            num += list1.size();
            HSSFWorkbook wb = new HSSFWorkbook();
            // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet sheet = wb.createSheet(name);
            // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow((int) 0);
            // 第四步，创建单元格，并设置值表头 设置表头居中
            HSSFCellStyle style = wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
            //  style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
            style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            style.setBorderRight(HSSFCellStyle.BORDER_THIN);
            style.setBorderTop(HSSFCellStyle.BORDER_THIN);
            // 生成一个字体
            HSSFFont font = wb.createFont();
            font.setFontHeightInPoints((short) 24);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
            // 把字体应用到当前的样式
            style.setFont(font);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("主题词");
            // cell.setCellStyle(style);
            HSSFCell cell1 = row.createCell(1);
            cell1.setCellValue("别名");
            //cell1.setCellStyle(style);
            // 第五步，写入实体数据 实际应用中这些数据从数据库得到，
            for (int i = 0; i < list1.size(); i++) {
                row = sheet.createRow((int) i + 1);
                Word word = list1.get(i);
                // 第四步，创建单元格，并设置值
                //String alias = "";
                row.createCell(0).setCellValue(word.getWord());
                String sql2 = "select word from tb_word where parent_id = " + word.getWordId() + " and word_id != " + word.getWordId() + " order by word ";
                List<Map> list2 = gm.findRecords(sql2);/*别名*/
                List<String> alias = new ArrayList<String>();
                if (list2.size() > 0) {
                    for (Map word1 : list2) {
                        if (word1.get("word") != null) {
                            alias.add(word1.get("word").toString());
                        }
                    }
                    if (alias.size() > 0) {
                        row.createCell(1).setCellValue(String.join(",", alias.toArray(new String[0])));
                    }
                }
            }
            File xlsFile = new File(url + "/dataFiles/" + name + ".xls");
            if (!xlsFile.exists()) {
                xlsFile.createNewFile();
            }
            FileOutputStream fout = new FileOutputStream(url + "/dataFiles/" + name + ".xls");
            try {
                sheet.autoSizeColumn(0, true);
                sheet.autoSizeColumn(1, true);
                File file = new File(url + "/dataFiles");
                if (!file.exists()) {
                    file.mkdir();
                }
                wb.write(fout);
            } catch (Exception e) {
                e.printStackTrace();
                fout.close();
                wb.close();
                return false;
            }
        }
        File file = new File(url + "/dataFiles");
        if (!file.exists()) {
            file.createNewFile();
        }
        File[] files = file.listFiles();
        List<File> list2 = new ArrayList<File>();
        if (files != null && files.length > 0) {
            Collections.addAll(list2, files);
        } else {
            return false;
        }
        File file1 = new File(url + "/zipFile");
        if (!file1.exists()) {
            file1.mkdir();
        }
        ZipUtil.createZip(list2, url + "/zipFile/" + special.getSpecialName() + "专题主题词.zip");
        long t2 = System.currentTimeMillis();
        logger.info(specialName + "专题专题词表导出完成，耗时：" + (t2 - t1)/1000 + "s,共导出：" + num + "个词");
        return true;
    }

    /*下载主题词文件*/
    @CrossOrigin( origins = "*" )
    @RequestMapping( "downloadWord" )
    public void downloadWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            long specialId = Long.parseLong(request.getParameter("specialId"));
            Special special = sm.selectByPrimaryKey(specialId);
            int b = 0;
            String name = special.getSpecialName();
            if (exportWords(specialId)) {
                response.setContentType("multipart/form-data;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment;fileName= " + URLEncoder.encode(special.getSpecialName() + "专题主题词", "UTF-8") + ".zip");
                ServletOutputStream out;
                out = response.getOutputStream();
                String url = fileDir + "Files/Words/" + name;
                File file1 = new File(url);
                if (!file1.exists()) {
                    file1.mkdir();
                }
                File file = new File(url + "/zipFile/" + name + "专题主题词.zip");
                FileInputStream inputStream = new FileInputStream(file);
                byte[] buffer = new byte[inputStream.available()];
                b = inputStream.read(buffer);
                out.write(buffer, 0, b);
                inputStream.close();
                out.close();
                out.flush();
            } else {
                response.setContentType("multipart/form-data;charset=UTF-8");
                response.setHeader("Content-Disposition", "attachment;fileName= " + URLEncoder.encode("暂无数据", "UTF-8") + ".zip");
                ServletOutputStream out;
                out = response.getOutputStream();
                out.close();
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*下载数据上传模板*/
    @CrossOrigin( origins = "*" )
    @RequestMapping( "downloadBook" )
    public void downloadBook(HttpServletRequest request, HttpServletResponse response) {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            long specialId = Long.parseLong(request.getParameter("specialId"));
            if (exportWords(specialId)) {
                Special special = sm.selectByPrimaryKey(specialId);
                //1.设置文件ContentType类型，这样设置，会自动判断下载文件类型
                response.setContentType("multipart/form-data;charset=UTF-8");
                //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
                response.setHeader("Content-Disposition", "attachment;fileName= book.zip");
                ServletOutputStream out;
                String filePath = fileDir + "Files/book.zip";
                File file = new File(filePath);
                FileInputStream inputStream = new FileInputStream(file);
                //3.通过response获取ServletOutputStream对象(out)
                out = response.getOutputStream();
                int b = 0;
                byte[] buffer = new byte[512];
                while (b != -1) {
                    b = inputStream.read(buffer);
                    out.write(buffer, 0, b);
                }
                inputStream.close();
                out.close();
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除文件夹
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除文件夹中文件
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }


    /*上传插图*/
    @CrossOrigin( origins = "*" )
    @RequestMapping( value = "uploadWordPic", method = RequestMethod.POST )
    public EdatResult uploadWordPic(HttpServletRequest request, HttpServletResponse response) throws Exception {
        try {
            ClientUtil.SetCharsetAndHeader(request, response);
            long wordID = Long.parseLong(request.getParameter("wordID"));
            Map map = new HashMap();
            File saveDirectory = new File(fileDir);
            String dirName = "Files/Words/Photos/";
            String bookPath = fileDir + "/" + dirName;
            File bookDirectory = new File(bookPath);
            if (!bookDirectory.exists()) {
                bookDirectory.mkdirs();
            }
            Collection<Part> parts = request.getParts();
            for (Part part : parts) {
                String fileType = part.getName();
                String fileName = part.getSubmittedFileName();
                if (fileName != null) {
                    InputStream is = part.getInputStream();
                    if (fileType.equals("file")) {
                        Word word = wm.selectByPrimaryKey(wordID);
                        String fileExtension = FilenameUtils.getExtension(fileName);
                        String name = wordID + "." + fileExtension;
                        if (!Arrays.asList(extensionPermit1).contains(fileExtension)) {
                            return EdatResult.build(1, "图片格式错误");
                        }
                        FileUtils.copyInputStreamToFile(is, new File(bookPath, name));
                        /*返回路径*/
                        map.put("url", dirName + name);
                        word.setPicUrl(dirName + name);
                        wm.updateByPrimaryKey(word);
                    }
                } else {
                    return EdatResult.build(1, "图片错误");
                }
            }
            return EdatResult.ok(map);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
        }
    }

    /*初始化文件夹*/
    @PostConstruct
    public void initFile() {
        try {
            fileDir = configUtil.getUrl();
            logDir = fileDir + "Files/log.txt";
            File file2 = new File(fileDir + "Files/Words/");
            if (!file2.exists()) {
                file2.mkdirs();
            }
            File file3 = new File(fileDir + "Files/Knowledge/");
            if (!file3.exists()) {
                file3.mkdir();
            }
            File file4 = new File(fileDir + "Files/Book/");
            if (!file4.exists()) {
                file4.mkdir();
            }
            File file = new File(logDir);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {

        }
    }

}
